package com.chatplus.application.web.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.chatplus.application.web.XSSFilterConfiguration;
import org.springframework.web.util.HtmlUtils;

import java.io.IOException;

//@Component
public class TurnRightObjectMapper extends ObjectMapper {

    public TurnRightObjectMapper(XSSFilterConfiguration.XSSFilterProperties properties) {

        SimpleModule simpleModule = new SimpleModule("XssStringJsonSerializer");

        if ("true".equalsIgnoreCase(properties.getEnabled())) {
            simpleModule.addSerializer(String.class, new JsonHtmlXssSerializer());
            simpleModule.addDeserializer(String.class, new JsonHtmlXssDeserializer());
        }

        this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(simpleModule)
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .registerModule(new JavaTimeModule());
    }

    static class JsonHtmlXssDeserializer extends JsonDeserializer<String> {

        public JsonHtmlXssDeserializer() {
            super();
        }

        @Override
        public Class<String> handledType() {
            return String.class;
        }

        @Override
        public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            String s = jsonParser.getText();
            if (s != null) {
                return HtmlUtils.htmlEscape(s.trim());
            }
            return null;
        }
    }

    static class JsonHtmlXssSerializer extends JsonSerializer<String> {

        public JsonHtmlXssSerializer() {
            super();
        }

        @Override
        public Class<String> handledType() {
            return String.class;
        }

        @Override
        public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (s != null) {
                String encodedValue = HtmlUtils.htmlEscape(s.trim());
                jsonGenerator.writeString(encodedValue);
            }
        }
    }

}
